package com.wocai.jrt.orgadmin.employee.action;

import java.text.SimpleDateFormat;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.vteba.utils.date.DateUtils;
import com.vteba.web.action.GenericAction;
import com.vteba.web.editer.StringEditor;
import com.wocai.jrt.orgadmin.employee.model.Checkin;
import com.wocai.jrt.orgadmin.employee.model.CheckinBean;
import com.wocai.jrt.orgadmin.employee.model.Employee;
import com.wocai.jrt.orgadmin.employee.service.spi.CheckinService;
import com.wocai.jrt.orgadmin.employee.service.spi.EmployeeService;
import com.wocai.jrt.orgadmin.utils.UserUtils;

/**
 * 员工签到控制器
 * @author yinlei
 * @date 2015-8-4 15:49:28
 */
@Controller
@RequestMapping("/checkin")
public class CheckinAction extends GenericAction<Checkin> {
	private static final Logger LOGGER = LoggerFactory.getLogger(CheckinAction.class);
	
	@Inject
	private CheckinService checkinServiceImpl;
	
	@Inject
	private EmployeeService employeeServiceImpl;
	
	/**
     * 获得员工签到List，初始化列表页。
     * @param model 参数
     * @return 员工签到List
     */
    @RequestMapping("/list")
    public String list(Checkin model, Map<String, Object> maps) {
        return "checkin/list";
    }
	
    @ResponseBody
    @RequestMapping("/query")
    public Map<String, Object> query(@RequestBody Employee employee) {
    	Map<String, Object> result = new HashMap<String, Object>();
    	try {
    		employee.setOrgId(UserUtils.getOrgId());
    		List<Employee> list = checkinServiceImpl.queryPageList(employee);
    		
    		// 统计的时候，不需要分页
    		long totalRecord = checkinServiceImpl.queryPageListCount(employee);
    		
    		if (LOGGER.isDebugEnabled()) {
    			LOGGER.debug("checkin query success.");
    		}
    		
    		// jQuery datatable 就是这样的参数
    		result.put("aaData", list); // 返回的数据
    		result.put("iTotalRecords", totalRecord); // 总记录数
    		result.put("iTotalDisplayRecords", totalRecord); // 显示的记录数
		} catch (Exception e) {
			LOGGER.error("checkin query error, msg=[{}]", e.getMessage());
		}
        return result;
    }

    /**
     * 查看员工签到详情页。
     * @param model 查询参数，携带ID
     * @return 员工签到详情页
     */
    @RequestMapping("/detail/{employeeId}/{startDate}")
    public String detail(Checkin model, Map<String, Object> maps) {
    	try {
    		Employee user = employeeServiceImpl.get(model.getEmployeeId());
            maps.put("user", user);
            maps.put("currentDate", DateUtils.toDateString(model.getStartDate(), "yyyy-MM-dd"));
		} catch (Exception e) {
			LOGGER.error("query record detail, errorMsg=[{}].", e.getMessage());
			return "common/error";
		}
        return "checkin/detail";
    }
    
    /**
     * 明细查询
     * @param model 查询参数，携带ID
     * @return 编辑页面
     */
    @ResponseBody
    @RequestMapping("/detailQuery")
    public List<Checkin> detailQuery(@RequestBody Checkin model) {
    	try {
    		CheckinBean params = new CheckinBean();
    		if (model.getStartDate() == null) {
    			DateTime dateTime = new DateTime();
    			dateTime = dateTime.minusDays(7);
    			model.setStartDate(dateTime.toDate());
    		}
    		if (model.getSignDate() == null) {
    			model.setSignDate(new Date());
    		}
    		params.createCriteria().andSignDateBetween(model.getStartDate(), model.getSignDate())
    		.andEmployeeIdEqualTo(model.getEmployeeId())
    		.andOrgIdEqualTo(UserUtils.getOrgId());
    		params.setOrderBy(" sign_date desc");
    		List<Checkin> list = checkinServiceImpl.queryForList(params);
    		
    		return list;
		} catch (Exception e) {
			LOGGER.error("detailQuery, errorMsg=[{}].", e.getMessage());
		}
        return Collections.emptyList();
    }
    
	@InitBinder
	protected void initBinder(WebDataBinder binder) {
		binder.registerCustomEditor(String.class, new StringEditor());
		binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}
}
